import React, { useState } from 'react';
import { Collapse, Table, Button, Popconfirm, Form, Input, Row, Col, Card, Select, Radio, InputNumber, Modal, Statistic, Empty, message } from 'antd';
import Limit from '@/components/Limit';
import EditorItem from '@/components/DragModal/EditorItem';
import { AEnodes } from '@/components/DragModal/formdoms';
import { CaretRightOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';


const App = () => {
    const [items, setItems] = useState([]);
    const [editkey, setEditkey] = useState(null);
    const [type, setType] = useState();
    const [name, setName] = useState(null);

    const { data, refresh } = useRequest(async () => {
        let res = await doFetch({
            url: '/projectType/list', params: {
                "name": "",
            }
        });
        return res?.data?.dataList ?? [];
    }, {
        onSuccess: (res) => {
            setItems(res)
        }
    })



    // Handle table row edit
    const handleEdit = (itemKey, recordKey, field, value) => {
        const newItems = items.map((item) => {
            if (item.id === itemKey) {
                const newData = item.data.map((row) =>
                    row.id === recordKey ? { ...row, [field]: value } : row
                );
                return { ...item, data: newData };
            }
            return item;
        });
        setItems(newItems);
    };

    // Add a new row to the table
    const handleAddRow = (e, item) => {
        e.stopPropagation();
        setModal(s => ({
            ...s,
            open: true,
            title: `添加 ${item.name} 下的节点`,
            projectTypeId: item.id,
            item: {}
        }))
    };

    // Delete a row from the table
    const handleDeleteRow = (itemKey, recordKey) => {
        run({ url: "/projectType/node/" + recordKey, params: {}, method: "DELETE" })
        message.success('删除成功');
    };

    // Handle panel edit
    const handlePanelEdit = (panelKey, field, value) => {
        const newItems = items.map((item) =>
            item.id === panelKey ? { ...item, [field]: value } : item
        );
        setItems(newItems);
    };

    // Add a new panel
    const handleAddPanel = () => {
        const newKey = `${items.length + 1}`;
        const newItem = {
            id: newKey,
            name: `新项目类型标题 ${newKey}`,
            deadline: 1,
            points: 0,
            standard: '',
            unit: 'day',
            block: 0,
            data: [],
        };
        setItems([...items, newItem]);
        setEditkey(newKey);
        setType('add');
    };

    // Delete a panel
    const handleDeletePanel = (panelKey) => {
        run({ url: "/projectType/" + panelKey, params: {}, method: "DELETE" });
        message.success('删除成功');
        refresh();
    };

    // Generate extra button for each panel to delete it
    const genExtra = (panelKey) => (
        <Popconfirm
            title="确认删除该项目类型吗?"
            onConfirm={() => handleDeletePanel(panelKey)}
            placement="bottomRight"
            onPopupClick={e => e.stopPropagation()}
        >
            <Button type="primary" danger onClick={e => e.stopPropagation()}>
                删除
            </Button>
        </Popconfirm>
    );

    // Render table for each panel
    const renderTable = (item) => {
        const columns = [
            {
                title: '类型',
                dataIndex: 'type',
                render: (text, record) => {
                    const opt = {
                        1: "标准",
                        2: "审批",
                    }
                    return opt[text]
                }
            },
            {
                title: '名称',
                dataIndex: 'name',
            },
            {
                title: '积分',
                dataIndex: 'points',
            },
            {
                title: '预计需要',
                dataIndex: 'deadline',
                render:(text)=> (text??"- ") + '天',
            },
            {
                title: '操作',
                dataIndex: 'action',
                width: 88,
                render: (_, record) => [
                    <a style={{ marginRight: 10 }} key='edit' onClick={() => {
                        setModal(s => ({
                            ...s,
                            open: true,
                            title: `编辑 ${item.name} 下的节点`,
                            item: record,
                            projectTypeId: item.id,
                        }))
                    }}>编辑</a>,
                    <Popconfirm
                        key='delete'
                        title="确认删除吗?"
                        onConfirm={() => handleDeleteRow(item.id, record.id)}
                        placement="bottomRight"
                    >
                        <a style={{ color: "red" }} type="link">删除</a>
                    </Popconfirm>
                ],
            },
        ];

        return (
            <Table
                size={"small"}
                dataSource={item.projectNodeList}
                columns={columns}
                pagination={false}
                rowKey="id"
                expandable={{
                    expandedRowRender: (record) => {
                        return (
                            <div style={{ display: "flex" }}>
                                <div style={{ flexShrink: 0, paddingTop: 8 }}>
                                    标准：
                                </div>
                                <Limit content={record?.standard}></Limit>
                            </div>
                        );
                    },
                }}
            />
        );
    };

    const col = { xs: 24, sm: 24, md: 24, lg: 24, xl: 12, xxl: 8 };
    const options = [
        { value: 'year', label: '年' },
        { value: 'quator', label: '季度' },
        { value: 'month', label: '月' },
        { value: 'week', label: '周' },
        { value: 'day', label: '天' },
    ]

    const [modal, setModal] = useState({
        open: false,
        footer: false,
        maskClosable: false,
        style: { top: 24 },
        onCancel: () => {
            setModal(s => ({
                ...s,
                open: false
            }))
        }
    });

    const { run, loading } = useRequest(doFetch, {
        manual: true,
        onSuccess: () => {
            refresh();
        },
    })


    return (
        <div>
            <Modal
                {...modal}
                destroyOnClose
            >
                <AEnodes
                    refresh={() => {
                        refresh?.();
                        modal.onCancel()
                    }}
                    initialValues={modal?.item}
                    projectTypeId={modal.projectTypeId}
                />
            </Modal>


            <div className="spread" style={{ marginBottom: 12 }}>
                <h2 className="ltitle">项目类型管理</h2>
                <Button type="primary" onClick={handleAddPanel} style={{ marginTop: 8, marginLeft: 12 }}>
                    添加项目类型
                </Button>
            </div>

            <div className="center">
                {
                    items?.length === 0 && <Empty style={{ marginTop: 88 }} >
                        <Button type="primary" onClick={handleAddPanel} style={{ marginTop: 8, marginLeft: 12 }}>
                            立即添加
                        </Button>
                    </Empty>
                }
            </div>
            <Row gutter={16}>

                {items?.map?.((item) => {
                    return (
                        <Col key={item.id} {...col} style={{ marginBottom: 12 }}>
                            <Card>
                                {
                                    editkey === item.id ?
                                        <Form
                                            key={item.id}
                                            layout="vertical"
                                            onFinish={(val) => {
                                                if (type === 'add') {
                                                    run({ url: "/projectType/save", params: { ...val, unit: item.unit } });
                                                } else {
                                                    run({ url: "/projectType/save", params: { ...val, unit: item.unit, id: type } });
                                                }
                                                setEditkey(null)
                                            }}
                                            initialValues={item}
                                        >
                                            <Row gutter={16}>
                                                <Col span={24} style={{ marginBottom: 12 }}>
                                                    <b style={{ fontSize: 16, fontWeight: "bold" }}>
                                                        {item.name}
                                                    </b>
                                                </Col>
                                                <Col span={8}>
                                                    <Form.Item
                                                        label="项目类型名称"
                                                        name={'name'}
                                                        required
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: '此项为必填项!',
                                                            },
                                                        ]}>
                                                        <Input
                                                            allowClear
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={8}>
                                                    <Form.Item label="服务期限" name="deadline">
                                                        <InputNumber style={{ width: "100%" }} addonAfter={<Select
                                                            value={item.unit}
                                                            popupMatchSelectWidth={68}
                                                            onChange={(value) => {
                                                                handlePanelEdit(item.id, 'unit', value);
                                                            }}
                                                            options={options}
                                                        />}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={8}>
                                                    <Form.Item label="消耗积木" name="block">
                                                        <InputNumber style={{ width: "100%" }} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={24}>
                                                    <Form.Item label="标准" name='standard'>
                                                        <EditorItem
                                                        />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={24} className='centerr gap12' style={{ paddingTop: 0 }}>
                                                    <Button onClick={() => {
                                                        setEditkey(null)
                                                    }}>
                                                        取消
                                                    </Button>
                                                    <Button loading={loading} type='primary' htmlType='submit'>
                                                        保存
                                                    </Button>
                                                </Col>
                                            </Row>
                                        </Form>
                                        : <Row>
                                            <Col span={24} style={{ marginBottom: 12 }}>
                                                <b style={{ fontSize: 16, fontWeight: "bold" }}>
                                                    {item.name}
                                                </b>
                                            </Col>
                                            <Col span={8} style={{ marginBottom: 12 }} className='center'>
                                                <Statistic title={'服务期限'} value={`${item.deadline}${options.find?.(it => it.value === item.unit)?.label}`}></Statistic>
                                            </Col>
                                            <Col span={8} style={{ marginBottom: 12 }} className='center'>
                                                <Statistic title={'消耗积木'} value={item.block}></Statistic>
                                            </Col>
                                            <Col span={8} style={{ marginBottom: 12 }} className='center'>
                                                <Statistic title={'项目积分'} value={item.points}></Statistic>
                                            </Col>
                                            <Col span={24}>
                                                <Collapse
                                                    style={{ marginTop: 12 }}
                                                    bordered={false}
                                                    expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                                                >
                                                    <Collapse.Panel
                                                        key={item.id}
                                                        header={"标准"}
                                                    >
                                                        <Limit content={item.standard}></Limit>
                                                    </Collapse.Panel>
                                                </Collapse>
                                            </Col>
                                            <Col span={24} style={{ marginBottom: 12 }}>
                                                <Collapse
                                                    style={{ marginTop: 12 }}
                                                    bordered={false}
                                                    expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                                                >
                                                    <Collapse.Panel
                                                        key={item.id}
                                                        header={`节点 ${item?.projectNodeList?.length} 条`}
                                                        extra={<Button type='link' size='small' className='sorts' onClick={(e) => handleAddRow(e, item)}>
                                                            新增节点
                                                        </Button>} // 添加删除按钮到 extra 属性
                                                    >
                                                        {renderTable(item)}
                                                    </Collapse.Panel>
                                                </Collapse>
                                            </Col>


                                            <Col span={24} className='centerr gap12'>
                                                <Button type='primary' onClick={() => {
                                                    setEditkey(item.id)
                                                    setType(item.id)
                                                }}>
                                                    编辑
                                                </Button>
                                                {genExtra(item.id)}
                                            </Col>
                                        </Row>
                                }

                            </Card>
                        </Col>
                    )
                })}
            </Row>
        </div>
    );
};

export default App;
